<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'"  @clickLeftBack="clickLeftBack" :title="$t('materials.simpleProductionReturn')" @clickRight="clickRight" scanType="1"></nav-bar-custom>
		</template>

		<template v-slot:gBody>
			<view class="barcodeSplitting">
				<!-- 扫描和库位选择模块 -->
				<view class="custom-form-card">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('hardwareOut.barcodeInformation')}}
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title">{{$t('hardwareOut.materialsDepartment')}}：</text>
						<superweiCombox style="text-align: right;" :candidates="data.peportmentList"
							:placeholder="$t('distributedOut.placeholder')" :isJSON="true" keyName="text" v-model="data.department"
							@select="departmentSelect"></superweiCombox>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">{{$t('distributedEnter.barcodeScan')}}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue" type="search"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick"></uni-easyinput>
					</view>
					<view class="custom-card-itemTwo" style="padding: 20rpx 0">
						<text class="item-info-title" style="padding-right: 40rpx"><text class="required-color"
								style="padding-right: 6rpx">*</text>{{$t('hardwareOut.rejectedMaterialQty')}}：</text>
						<uni-easyinput disabled class="uni-mt-5" type="number" v-model="data.allInputNum">
						</uni-easyinput>
						<!-- <view class="card-checkBtn bottomBtn-bgcolor-green" @click="confirm">确定</view> -->
					</view>
				</view>
				<!-- card模块 -->
				<!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
				<view class="custom-form-card">
					<uni-collapse v-if="data.scanInfo" v-model="data.value">
						<uni-collapse-item titleBorder="none" :show-animation="true">
							<template v-slot:title>
								<view class="custom-card-title">
									<text class="title-line"></text>
									{{$t('distributedOut.atPresent')}}
								</view>
							</template>
							<view class="content" style="margin-top: 10rpx;">
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{ data.scanInfo.materialCode }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>{{ data.scanInfo.materialName }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50" style="width: 100%;">
										<text class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{ data.scanInfo.materialSpec || '' }}
									</view>
								</view>
								<view class="custom-card-itemOne">
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{ data.scanInfo.currentQty }}
									</view>
									<view class="card-item-50">
										<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{ data.scanInfo.unit }}
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
				<!-- </scroll-view> -->
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelSubmit">{{$t('calendar.submit')}}</view>
				</view>
			</view>
			<!-- 弹框填写数量 -->
			<uni-popup ref="inputDialog" type="center">
				<view v-if="data.scanInfo" class="input-dialog-box">
					<view class="input-dialog-content">
						<view class="input-dialog-item">
							{{$t('distributedEnter.materialCode')}}:{{ data.scanInfo.materialCode }}
						</view>
						<view class="input-dialog-item">
							{{$t('distributedEnter.materialName')}}:{{ data.scanInfo.materialName }}
						</view>
						<view class="input-dialog-item">
							{{$t('distributedEnter.materialSpec')}}:{{ data.scanInfo.materialSpec || '' }}
						</view>
						<view class="input-dialog-item">
							{{$t('distributedEnter.uom')}}:{{ data.scanInfo.unit }}
						</view>
						<view class="gui-form-item" style="color: #dd524d">
							<text>{{$t('hardwareOut.outQty')}}：</text>
							<view>
								<input type="number" style="margin: 8rpx 0;" class="gui-form-input"
									v-model="data.scanInfo.inputNum" :placeholder="$t('materials.pleaseEnterThe')" />
							</view>
						</view>
					</view>
					<view class="input-dialog-footer">
						<view class="input-dialog-button" @click="cancelFn">
							{{$t('popup.cancel')}}
						</view>
						<view class="input-dialog-button dialog-button-left" @click="confirmFn">
							{{$t('popup.confirm')}}
						</view>
					</view>
				</view>
			</uni-popup>
		</template>
	</gui-page>
</template>

<script setup>
import { navigate } from '@/utils/routerSkip.js';
import superweiCombox from '@/components/superweiCombox';
import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import { useStore } from "vuex";
import pdaScan from '@/hooks/pdaScan.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_COMMIT, OPERATION_SCAN } from '@/constant/index.js'
import {
	ref,
	reactive,
	onMounted,
	watch,
	computed,
	toRaw
} from 'vue';
import { simpleProductionReturn, wmsSelectWmsBarcodeInfo } from '@/api/api.js'
import { onBackPress } from '@dcloudio/uni-app';
//JS国际化引入
import { useI18n } from 'vue-i18n';
components: {
	superweiCombox
}
const { t } = useI18n();

let store = useStore();
//页面弹框输入数量使用的变量
let inputDialog = ref(null)
const { scan } = pdaScan()
let data = reactive({
	allInputNum: null,//总数量
	value: ['0'],
	wjOutScanList: [],//扫描存储数组
	warehouseName: '',// 仓库
	scanInfo: undefined, // 当前扫描信息
	locationCode: '',// 库位
	peportmentList: [],//领料人数组
	deportmentCode: '', //领料部code
	department: '', //领料部门
	scanValue: '',//扫码信息
	inputNum: null,//数量
});
onMounted(() => {
	// 获取库位
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	getInitData()
})
const getInitData = async () => {
	// 获取领料人数据
	data.peportmentList = await getDataDictionaryFn('Deportment')
	let tepSelect1 = pitchOnFn(data.peportmentList)
	if (tepSelect1.length == 0) return
	data.department = tepSelect1[0].text // 默认选中第一个 text
	data.deportmentCode = tepSelect1[0].value  // 默认选中第一个 value
}
// 监听手动赋值
const computeData = () => {
	data.allInputNum = null
	if (!data.scanInfo && data.wjOutScanList.length > 0) {
		data.scanInfo = data.wjOutScanList[0]
	}
	if (data.scanInfo && data.wjOutScanList.length == 0) {
		data.scanInfo = undefined
		data.inputNum = null
	}
	console.log(data.wjOutScanList)
	data.wjOutScanList.forEach(element => {
		data.allInputNum += Number(element.inputNum)
	});
}
data.wjOutScanList = computed(() => {
	return store.state.hardWare.simpleList
})
// 监听returnSpScanList变化
watch(() => data.wjOutScanList, () => {
	computeData()
}, {
	immediate: true,
	deep: true
});
//监听当前扫描信息的变化
watch(() => data.scanInfo, (newVal) => {
	if (!newVal) {
		data.warehouseName = ''
		data.locationCode = ''
		data.inputNum = null
	} else {
		data.warehouseName = newVal.warehouseName
		data.locationCode = newVal.locationCode
	}
}, {
	immediate: true,
	deep: true
});
// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
onBackPress((options) => {
	if (options.from == 'backbutton') {
		navBackCheck()
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	navBackCheck()
}
const navBackCheck = () =>{
	if(!data.wjOutScanList.length){
		uni.navigateBack({
			delta: 1
		});
		return  true
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.dispatch('hardWare/resetSimpleList')
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
     
	 return true
}
// 弹框的取消按钮
const cancelFn = () => {
	data.scanInfo = undefined
	inputDialog.value.close()
}
//弹框的确定按钮
const confirmFn = () => {
	if(data.scanInfo.inputNum == null){
		// t('JsInternational.plsReturn')
		uni.showToast({ title:t('materials.pleaseEnterThe'), icon: "none" });
		return
	}
	// t('JsInternational.qtyCant')
	if (Number(data.scanInfo.inputNum) <= 0) {
		uni.showToast({ title: t('materials.outgoingQuantityCannot'), icon: "none" });
		return
	}
	store.dispatch('hardWare/setWjOutScanList', data.scanInfo)
	uni.showToast({ title: t('JsInternational.dataSaved'), icon: "none" });
	inputDialog.value.close();
}
// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	let arr = data.wjOutScanList.filter(x => x.barcode == code)
	if (arr.length > 0) {
		uni.showToast({ title: t('JsInternational.scanInputBarcode'), icon: "none" });
		return
	}
	data.scanValue = code
	let parmes = {
		barcode: code,
		selectType: 'simpleProductionReturn',
		receiptId: data.id,
	}
	wmsSelectWmsBarcodeInfo(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '简单生产退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode:res.status,//返回状态
				errorMessage:res.message,//错误信息
				isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType:OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.status == 200) {
			if(res.data.currentQty == 0) {
				uni.showToast({ title:t('materials.scannedBarcodesCannot'), icon: "none" });
				return
			}
			data.scanInfo = res.data
			data.scanInfo.inputNum = res.data.currentQty
			store.dispatch('hardWare/setSimpleScanList', data.scanInfo)
			// inputDialog.value.open()
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/simpleMaterial/simpleMaterialReturnRecord'
	})
}
const departmentSelect = (e) => {
	data.deportmentCode = e.value
}
//确定按钮
const handelSubmit = () => {

	if (data.wjOutScanList.length == 0) {
		uni.showToast({ title: t('JsInternational.scanInput'), icon: "none" });
		return
	}
	if (data.department.length == 0) {
		uni.showToast({ title: t('JsInternational.chooseDept'), icon: "none" });
		return
	}
	let tepData = toRaw(data.wjOutScanList)
	let tep = []
	tepData.forEach(x=>{
		tep.push({
			pickUpQty: x.inputNum,
			id: x.id,
		})
	})
	console.log(tep)
	let parmes = {
		wmsBarcodes:tep
	}
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	simpleProductionReturn(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '简单生产退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode:res.status,//返回状态
				errorMessage:res.message,//错误信息
				isPass:res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType:OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			data.scanInfo = null
			//删除已提交的数据
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.dispatch('hardWare/resetSimpleList')
			data.scanInfo = null
			data.scanValue = null
			data.allInputNum = null
			// navigateBack()
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.page-bottom-box {
	position: absolute;
	left: 0rpx;
	bottom: 0rpx;
	width: 100%
}
.item-info-title{
	width: 90px !important;
}
</style>
